//
//  VRAuthenticationViewController.m
//  KeepAccount
//
//  Created by Veer on 2018/1/10.
//  Copyright © 2018年 Veer. All rights reserved.
//

#import "VRAuthenticationViewController.h"

#import "UIImage+VR.h"
#import <CoreTelephony/CTCellularData.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "FCPPSDK.h"

@interface VRAuthenticationViewController ()

@property (nonatomic, weak) UIImageView *frontImgView;
@property (nonatomic, weak) UIImageView *backImgView;
@property (nonatomic, weak) UIImageView *faceImgView;

@property (nonatomic, copy) NSString *typeStr;


// 正面图片
@property (nonatomic, strong) UIImage *frontImage;
@property (nonatomic, assign) BOOL frontImgCorrectness;
@property (nonatomic, strong) NSDictionary *frontDict;
// 反面图片
@property (nonatomic, strong) UIImage *identityImage;
@property (nonatomic, assign) BOOL identityImgCorrectness;
@property (nonatomic, strong) NSDictionary *identityDict;
// 人脸图片
@property (nonatomic, strong) UIImage *faceImage;
@property (nonatomic, assign) BOOL faceImgCorrectness;
@property (nonatomic, strong) NSDictionary *faceDict;
@property (nonatomic, strong) NSDictionary *compareDict;

@end

@implementation VRAuthenticationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = RGB(242, 243, 249);
    
    [self setupNav];
    [self setupSubView];
}

- (void)setupNav
{
    UIView *navBarView = [[UIView alloc] init];
    navBarView.backgroundColor = MAINColor;
    [self.view addSubview:navBarView];
    [navBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(NAVIGATION_BAR_HEIGHT);
    }];
    
    // 保存
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [backBtn addTarget:self action:@selector(onBackBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"toolbar_navigation_icon_normal"] forState:UIControlStateNormal];
//    backBtn.imageEdgeInsets = UIEdgeInsetsMake(2, 0, 2, 0);
    [navBarView addSubview:backBtn];
    [backBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.centerY.mas_equalTo(navBarView.mas_bottom).offset(-22);
        make.width.mas_equalTo(20);
        make.height.mas_equalTo(20);
    }];
    
    // 标题
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"身份证认证";
    titleLbl.font = VRFont(15);
    titleLbl.textColor = [UIColor blackColor];
    titleLbl.textAlignment = NSTextAlignmentCenter;
    [navBarView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(navBarView);
        make.centerY.mas_equalTo(navBarView.mas_bottom).offset(-22);
    }];
}

- (void)setupSubView
{
    
    // 上传
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"为了保证识别准确度，请保持手机竖直拍摄照片";
    titleLbl.font = VRFont(14);
    titleLbl.textColor = [UIColor redColor];
    titleLbl.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT + 20);
        make.centerX.mas_equalTo(self.view);
    }];
    
    // 上传
//    UILabel *titleLbl = [[UILabel alloc] init];
//    titleLbl.text = @"请上传您的身份证照片";
//    titleLbl.font = VRFont(15);
//    titleLbl.textColor = [UIColor blackColor];
//    titleLbl.textAlignment = NSTextAlignmentCenter;
//    [self.view addSubview:titleLbl];
//    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(NAVIGATION_BAR_HEIGHT + 20);
//        make.centerX.mas_equalTo(self.view);
//    }];
    
    // 正面照
    UIImageView *frontImgView = [[UIImageView alloc] init];
    frontImgView.userInteractionEnabled = YES;
    frontImgView.contentMode = UIViewContentModeScaleAspectFill;
    frontImgView.tag = 100;
    frontImgView.image = [UIImage imageNamed:@"front_idcard"];
    frontImgView.layer.masksToBounds = YES;
    [self.view addSubview:frontImgView];
    self.frontImgView = frontImgView;
    [frontImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleLbl.mas_bottom).offset(10);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(self.view.mas_centerX).offset(-5);
        make.height.mas_equalTo(frontImgView.mas_width).multipliedBy(413.0 / 600);
    }];
    
    // 反面照
    UIImageView *backImgView = [[UIImageView alloc] init];
    backImgView.userInteractionEnabled = YES;
    backImgView.contentMode = UIViewContentModeScaleAspectFill;
    backImgView.tag = 101;
    backImgView.image = [UIImage imageNamed:@"back_idcard"];
    backImgView.layer.masksToBounds = YES;
    [self.view addSubview:backImgView];
    self.backImgView = backImgView;
    [backImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(titleLbl.mas_bottom).offset(10);
        make.left.mas_equalTo(self.view.mas_centerX).offset(5);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(backImgView.mas_width).multipliedBy(413.0 / 600);
    }];
    
    // 脸部照
    UIImageView *faceImgView = [[UIImageView alloc] init];
    faceImgView.userInteractionEnabled = YES;
    faceImgView.contentMode = UIViewContentModeScaleAspectFill;
    faceImgView.tag = 102;
    faceImgView.image = [UIImage imageNamed:@"hand_idcard"];
    faceImgView.layer.masksToBounds = YES;
    [self.view addSubview:faceImgView];
    self.faceImgView = faceImgView;
    [faceImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(frontImgView.mas_bottom).offset(10);
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(faceImgView.mas_width).multipliedBy(555.0 / 800);
    }];
    
    // 保存
    UIButton *saveBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    saveBtn.backgroundColor = RGB(254, 216, 94);
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    saveBtn.titleLabel.font = VRFont(16);
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveBtn setBackgroundImage:[UIImage imageWithColor:RGB(254, 216, 94)] forState:UIControlStateNormal];
    saveBtn.layer.cornerRadius = 4;
    saveBtn.layer.masksToBounds = YES;
    [saveBtn addTarget:self action:@selector(onSaveBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.bottom.mas_equalTo(-60);
        make.height.mas_equalTo(45);
    }];
    
    UITapGestureRecognizer *tapGesture0 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTagGesture:)];
    UITapGestureRecognizer *tapGesture1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTagGesture:)];
    UITapGestureRecognizer *tapGesture2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTagGesture:)];
    [frontImgView addGestureRecognizer:tapGesture0];
    [backImgView addGestureRecognizer:tapGesture1];
    [faceImgView addGestureRecognizer:tapGesture2];
}


- (void)takePhotoFromCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        [imagePicker.navigationBar setBackgroundImage:[UIImage imageWithColor:RGBA(255, 255, 255, 0.95)] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
        //        [imagePicker.navigationBar setBackgroundImage:[UIImage imageWithColor:[NAVColor]] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
        
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        imagePicker.allowsEditing = YES;
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}


#pragma mark - network
- (void)uploadImages
{
    
    NSMutableDictionary *subParam1 = [NSMutableDictionary dictionary];
    subParam1[@"type"] = @(1);
    subParam1[@"imgBase64"] = [UIImage compressImage:self.frontImage toSize:CGSizeMake(2000, 2000) toMaxFileSize:1024 * 1024].base64String;//self.frontImage.base64String;
    subParam1[@"extra"] = self.frontDict;
    
    NSMutableDictionary *subParam2 = [NSMutableDictionary dictionary];
    subParam2[@"type"] = @(2);
    subParam2[@"imgBase64"] = [UIImage compressImage:self.identityImage toSize:CGSizeMake(2000, 2000) toMaxFileSize:1024 * 1024].base64String;//self.identityImage.base64String;
    subParam2[@"extra"] = self.identityDict;
    
    NSMutableDictionary *subParam3 = [NSMutableDictionary dictionary];
    subParam3[@"type"] = @(3);
    subParam3[@"imgBase64"] = [UIImage compressImage:self.faceImage toSize:CGSizeMake(2000, 2000) toMaxFileSize:1024 * 1024].base64String;//self.faceImage.base64String;
    subParam3[@"extra"] = self.faceDict;
    
//    NSString *jsonStr = [self convertToJsonData:@[subParam1, subParam2, subParam3]];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"imgs"] = @[subParam1, subParam2, subParam3];//jsonStr;
    param[@"userid"] = self.userid;
    param[@"compareResult"] = self.compareDict;//[self convertToJsonData:self.compareDict];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.mode = MBProgressHUDModeText;
    hud.label.text = @"正在认证,请等待1-3分钟";
    
    AFHTTPSessionManager *sessionMgr = [AFHTTPSessionManager manager];
    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"application/json", nil];
    //    sessionMgr.responseSerializer.acceptableContentTypes = [[NSSet  alloc] initWithObjects:@"text/html", nil];

    AFJSONResponseSerializer *json =[AFJSONResponseSerializer serializer];
    json.removesKeysWithNullValues = YES;
    sessionMgr.responseSerializer = json;

    sessionMgr.requestSerializer = [AFJSONRequestSerializer serializer];//[AFHTTPRequestSerializer serializer];

    // 设置超时时长
    [sessionMgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    sessionMgr.requestSerializer.timeoutInterval = 60.0;
    [sessionMgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];

    WeakSelf(weakSelf)
    // API_uploadImageUrl
    [sessionMgr POST:self.sfsbJk parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {


    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        // hud
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"responseObject:%@", responseObject);

        NSInteger struts = [responseObject[@"fh"] integerValue];
        if (struts == 1){

            [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            [weakSelf dismissViewControllerAnimated:NO completion:nil];
            if ([weakSelf.delegate respondsToSelector:@selector(authenticationSaveSuccessed)]) {
                [weakSelf.delegate authenticationSaveSuccessed];
            }
        }else if(struts == 2){

            [SVProgressHUD showErrorWithStatus:@"您已经认证过了"];
        }else if(struts == 0){

            [SVProgressHUD showErrorWithStatus:@"参数为空"];
        }else if(struts == 3){
            
            [SVProgressHUD showErrorWithStatus:@"此身份证已经存在！"];
        }else{

            [SVProgressHUD showErrorWithStatus:@"未知错误"];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSLog(@"error:%@", error);
        [SVProgressHUD dismiss];
        if (error.code == -1009) {  // 网络连接错误

            [SVProgressHUD showErrorWithStatus:@"网络连接错误"];
        }else if (error.code == -1001){ // 链接超时

            [SVProgressHUD showErrorWithStatus:@"请求超时"];
        }else{

            [SVProgressHUD showErrorWithStatus:@"请求错误"];
        }
    }];
    
}


- (void)compareFaceWithOther
{
    
    FCPPFace *face1 = [[FCPPFace alloc] initWithImage:self.frontImage];
    FCPPFace *face2 = [[FCPPFace alloc] initWithImage:self.faceImage];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = @"正在认证,请等待1-3分钟";
    
    WeakSelf(weakSelf)
    [face1 compareFaceWithOther:face2 completion:^(id info, NSError *error) {
        
        NSLog(@"compareFaceWithOther:%@", info);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (info) {
            
            weakSelf.compareDict = info;
            NSArray *face1 = info[@"faces1"];
            NSArray *face2 = info[@"faces2"];
            if (face1.count == 0) {
                [SVProgressHUD showErrorWithStatus:@"没有识别到脸部照片"];
                return ;
            }
            if(face2.count == 0){
                [SVProgressHUD showErrorWithStatus:@"没有识别到脸部照片"];
                return;
            }
            
            NSNumber *confidence = info[@"confidence"];
            NSDictionary *thresholds = info[@"thresholds"];
            
            CGFloat confidenceValue = confidence.floatValue;
            CGFloat maxThreshold = [thresholds[@"1e-5"] floatValue];
//            CGFloat midThreshold = [thresholds[@"1e-4"] floatValue];
            CGFloat minThreshold = self.sfzsbd.length > 0 ? [self.sfzsbd floatValue] : [thresholds[@"1e-3"] floatValue];
            
            // 用户可根据自己的业务场景,选择不同的阈值.要求严格选择max,宽松则选择min
            if (confidenceValue >= maxThreshold) {
                // 可能性高
                [weakSelf uploadImages];
            }else if (confidenceValue <= minThreshold){
                // 可能性低
                [SVProgressHUD showErrorWithStatus:@"身份证和面部照片不匹配"];
            }else{
                // 可能性一般
                [SVProgressHUD showErrorWithStatus:@"身份证和面部照片不匹配"];
            }
        }else{
            NSData *errorData = error.userInfo[@"com.alamofire.serialization.response.error.data"];
            if (errorData) {
                NSString *errorStr = [[NSString alloc] initWithData:errorData encoding:NSUTF8StringEncoding];
                //                self.textView.text = errorStr;
            }else{
                //                self.textView.text = @"网络请求失败";
            }
            [SVProgressHUD showErrorWithStatus:@"网络请求失败，请重试"];
        }
    }];
}



- (void)handleIDCardImage:(UIImage *)image{
    
    FCPPOCR *ocr = [[FCPPOCR alloc] initWithImage:image];
    NSLog(@"%f", ocr.image.imageData.length/1024.0/1024.0);
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    WeakSelf(weakSelf)
    [ocr ocrIDCardCompletion:^(id info, NSError *error) {
        
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        NSLog(@"result:%@", info);
        if (info) {
            
            NSArray *array = info[@"cards"];
            if (array.count > 0) {
                
                NSDictionary *idcardInfo = [array firstObject];
                if (weakSelf.typeStr.integerValue == 1 && [idcardInfo[@"side"] isEqualToString:@"front"]) {   // 正面
                    weakSelf.frontImgCorrectness = YES;
                    weakSelf.frontDict = [array firstObject];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        weakSelf.frontImgView.image = image;
                    });
                }else if (weakSelf.typeStr.integerValue == 2 && [idcardInfo[@"side"] isEqualToString:@"back"]){  // 反面
                    weakSelf.identityImgCorrectness = YES;
                    weakSelf.identityDict = [array firstObject];
                    dispatch_async(dispatch_get_main_queue(), ^{
                        weakSelf.backImgView.image = image;
                    });
                }else{
                    if (weakSelf.typeStr.integerValue == 1) {
                        [SVProgressHUD showErrorWithStatus:@"请上传正确的身份证正面照片"];
                    }else{
                        [SVProgressHUD showErrorWithStatus:@"请上传正确的身份证反面照片"];
                    }
                }
            }else{
                if (weakSelf.typeStr.integerValue == 1) {
                    [SVProgressHUD showErrorWithStatus:@"请上传正确的身份证正面照片"];
                }else{
                    [SVProgressHUD showErrorWithStatus:@"请上传正确的身份证反面照片"];
                }
            }
        }else{
            [SVProgressHUD showErrorWithStatus:@"网络请求失败，请重试"];
        }
    }];
}


- (void)handleImage:(UIImage *)image{
    
    //检测人脸
    FCPPFaceDetect *faceDetect = [[FCPPFaceDetect alloc] initWithImage:image];
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    //需要获取的属性
    NSArray *att = @[@"facequality"];
    [faceDetect detectFaceWithReturnLandmark:YES attributes:att completion:^(id info, NSError *error) {
        
        [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        
        if (info) {
            NSArray *array = info[@"faces"];
            if (array.count > 0) {
                
                NSDictionary *faceInfo = [array firstObject];
                NSDictionary *att = faceInfo[@"attributes"];
                //显示json
                NSString *value = [self largeKeyWith:att[@"facequality"]];
                //                NSString *score = att[@"facequality"][@"value"];
                if ([value isEqualToString:@"value"]) {
                    //                    value = [NSString stringWithFormat:@"人脸质量分数: %.2f, 可以用做人脸比对",score.floatValue];
                    weakSelf.faceImgCorrectness = YES;
                    weakSelf.faceDict = faceInfo;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        weakSelf.faceImgView.image = image;
                    });
                }else{
                    [SVProgressHUD showErrorWithStatus:@"请上传正确的脸部照片"];
                }
            }else{
                [SVProgressHUD showErrorWithStatus:@"请上传正确的脸部照片"];
            }
        }else{
//            [SVProgressHUD showErrorWithStatus:@"请上传正确的脸部照片"];
            [SVProgressHUD showErrorWithStatus:@"网络请求失败，请重试"];
        }
    }];
}


- (void)takePhotoFromPhotoLibrary
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        UIImagePickerController *imagePicker = [UIImagePickerController new];
        [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
        //        imagePicker.navigationBar.backgroundColor = [UIColor whiteColor];
        [imagePicker.navigationBar setBackgroundImage:[UIImage imageWithColor:RGBA(255, 255, 255, 0.95)] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
        //        NSDictionary *dic = [XCommonMethod X_ReadJsonFileWithNFileName:[TXSakuraManager getSakuraCurrentName]];
        //        [imagePicker.navigationBar setBackgroundImage:[UIImage imageWithColor:NAVColor] forBarPosition:UIBarPositionTopAttached barMetrics:UIBarMetricsDefault];
        
        imagePicker.allowsEditing = YES;
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.mediaTypes = @[(NSString *)kUTTypeImage];
        imagePicker.navigationBar.barTintColor = [UIColor colorWithRed:20.f/255.0 green:24.0/255.0 blue:38.0/255.0 alpha:1];
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
}

//取出value值最大的对应的key
- (NSString *)largeKeyWith:(NSDictionary *)dic{
    __block NSString *largeKey = nil;
    __block CGFloat maxValue = 0;
    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj floatValue] > maxValue) {
            maxValue = [obj floatValue];
            largeKey = key;
        }
    }];
    return largeKey;
}


#pragma mark - action
- (void)onSaveBtnClick:(UIButton *)sender
{

    if (self.frontImage == nil) {
        [SVProgressHUD showErrorWithStatus:@"请上传身份证正面照"];
        return;
    }else if (self.identityImage == nil){
        [SVProgressHUD showErrorWithStatus:@"请上传身份证反面照"];
        return;
    }else if (self.faceImage == nil){
        [SVProgressHUD showErrorWithStatus:@"请上传脸部照"];
        return;
    }
    
    if (self.frontDict == nil) {
        [SVProgressHUD showErrorWithStatus:@"请上传正确的身份证正面照片"];
        return;
    }else if (self.identityDict == nil){
        [SVProgressHUD showErrorWithStatus:@"请上传正确的身份证反面照片"];
        return;
    }else if (self.faceDict == nil){
        [SVProgressHUD showErrorWithStatus:@"请上传正确的面部照"];
        return;
    }
    
    [self compareFaceWithOther];
}

- (void)onBackBtnClick:(UIButton *)sender
{
    [self dismissViewControllerAnimated:NO completion:nil];
}

- (void)handleTagGesture:(UITapGestureRecognizer *)tapRec
{
    if (tapRec.view.tag == 100) {
        
        self.typeStr = @"1";
    }else if (tapRec.view.tag == 101){
        
        self.typeStr = @"2";
    }else if (tapRec.view.tag == 102){
        
        self.typeStr = @"3";
    }
    [self takePhotoFromCamera];
}

#pragma mark - UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *resultImage = info[UIImagePickerControllerEditedImage];
    if (self.typeStr.integerValue == 1) {
        
        self.frontImage = resultImage;
        [self handleIDCardImage:resultImage];
    }else if (self.typeStr.integerValue == 2){
        
        self.identityImage = resultImage;
        [self handleIDCardImage:resultImage];
    }else if (self.typeStr.integerValue == 3){
        
        self.faceImage = resultImage;
        [self handleImage:resultImage];
    }
    //    UIImage *image = [UIImage compressImage:resultImage toSize:CGSizeMake(400, 400) toMaxFileSize:1024 * 1024];
    //    NSData *imgData = UIImageJPEGRepresentation(image, 1.0f);
    //    NSString *encodedImageStr = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    //
    //    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    //    path = [path stringByAppendingString:@"/header.jpeg"];
    //    path = [path stringByAppendingFormat:@"/%ld.jpeg", (long)[[NSDate date] timeIntervalSince1970]];
    //    [imgData writeToFile:path atomically:YES];
    
    //    JSValue *value = [self.jsContext[@"setImg"] callWithArguments:@[path]];
    //    if (self.typeStr.length > 0) {
    //        JSValue *value = [self.jsContext[@"onGetPic"] callWithArguments:@[self.typeStr, path]];
    //    }
    //
    //    [self uploadImageWithCard:@"" base64:encodedImageStr];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - tool
// 字典转json字符串方法

-(NSString *)convertToJsonData:(id)dict

{
    
    NSError *error;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    
    NSString *jsonString;
    
    if (!jsonData) {
        
        NSLog(@"%@",error);
        
    }else{
        
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
        
    }
    
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0, jsonString.length};
    
    //去掉字符串中的空格
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    
    NSRange range2 = {0,mutStr.length};
    
    //去掉字符串中的换行符
    
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
}

- (NSString *)base64StringWithImage:(UIImage *)image{
    
    NSData *data = UIImageJPEGRepresentation(image, 1.0);
    return [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
}


@end
